<template>
  <div class="meme-container">
    <a-card class="meme-card" :bordered="false">
<!--      <template #title>-->
<!--        <div class="page-header">-->
<!--          <div class="title-section">-->
<!--            <span class="emoji-title">😂</span>-->
<!--            <span class="main-title">表情包生成器</span>-->
<!--            <span class="emoji-title">🎭</span>-->
<!--          </div>-->
<!--          <div class="subtitle">海量表情包，一键生成分享</div>-->
<!--        </div>-->
<!--      </template>-->

      <!-- 搜索区域 -->
      <div class="search-area">
        <a-radio-group v-model:value="searchType" button-style="solid" class="search-type">
          <a-radio-button :value="1">
            <smile-outlined />
            随机表情
          </a-radio-button>
          <a-radio-button :value="2">
            <search-outlined />
            关键词搜索
          </a-radio-button>
        </a-radio-group>

        <div class="search-input-area" v-if="searchType === 2">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="输入关键词搜索表情包"
            enter-button
            :loading="loading"
            @search="searchMemes"
            :disabled="loading"
            class="search-input"
            allow-clear
          />
          <div class="search-tags">
            <span class="tag-label">热门标签：</span>
            <a-tag
              v-for="tag in popularTags"
              :key="tag"
              color="orange"
              @click="quickSearch(tag)"
              class="popular-tag"
            >
              {{ tag }}
            </a-tag>
          </div>
        </div>

        <div class="random-options" v-else>
          <span class="option-label">数量：</span>
          <a-slider
            v-model:value="randomLimit"
            :min="1"
            :max="20"
            :marks="{ 1: '1', 5: '5', 10: '10', 15: '15', 20: '20' }"
            class="limit-slider"
          />
          <a-button
            type="primary"
            @click="getRandomMemes"
            :loading="loading"
            class="random-btn"
          >
            <template #icon><thunderbolt-outlined /></template>
            生成随机表情包
          </a-button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin tip="正在获取表情包...">
          <div class="loading-content">
            <a-skeleton active :paragraph="{ rows: 5 }" />
          </div>
        </a-spin>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <a-result
          status="error"
          title="获取表情包失败"
          :sub-title="error"
        >
          <template #extra>
            <a-button type="primary" @click="searchType === 1 ? getRandomMemes() : searchMemes()">
              重试
            </a-button>
          </template>
        </a-result>
      </div>

      <!-- 表情包展示区域 -->
      <div v-else-if="memeData && memeData.res && memeData.res.length > 0" class="meme-content">
        <div class="result-info" v-if="searchType === 2">
          <a-alert
            type="success"
            show-icon
            :message="`找到 ${memeData.count || 0} 个「${searchKeyword}」相关表情包`"
          />
        </div>

        <div class="meme-grid">
          <div v-for="(url, index) in memeData.res" :key="index" class="meme-item">
            <a-card hoverable class="meme-card-item">
              <template #cover>
                <div class="meme-image-container">
                  <img
                    :src="url"
                    :alt="`表情包${index+1}`"
                    class="meme-image"
                    @error="handleImageError($event, index)"
                    @click="previewImage(url)"
                  />
                  <div class="meme-overlay">
                    <a-button type="primary" shape="circle" @click.stop="previewImage(url)">
                      <template #icon><eye-outlined /></template>
                    </a-button>
                    <a-button type="primary" shape="circle" @click.stop="downloadImage(url, index)">
                      <template #icon><download-outlined /></template>
                    </a-button>
                    <a-button type="primary" shape="circle" @click.stop="copyImageUrl(url)">
                      <template #icon><copy-outlined /></template>
                    </a-button>
                  </div>
                </div>
              </template>
              <a-card-meta>
                <template #title>
                  <div class="meme-title">
                    表情包 #{{ index + 1 }}
                    <span class="meme-emoji">{{ getRandomEmoji() }}</span>
                  </div>
                </template>
                <template #description>
                  <div class="meme-url">
                    <a-tooltip :title="url">
                      <div class="url-text">{{ truncateUrl(url) }}</div>
                    </a-tooltip>
                    <a-button
                      type="link"
                      size="small"
                      @click="copyImageUrl(url)"
                      class="copy-btn"
                    >
                      复制链接
                    </a-button>
                  </div>
                </template>
              </a-card-meta>
            </a-card>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-area" v-if="searchType === 2 && memeData.maxpage > 1">
          <a-pagination
            v-model:current="currentPage"
            :total="parseInt(memeData.count || 0)"
            :pageSize="5"
            @change="handlePageChange"
            show-quick-jumper
            :show-total="total => `共 ${total} 个表情包`"
          />
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <a-button
            type="primary"
            @click="searchType === 1 ? getRandomMemes() : searchMemes()"
            :loading="loading"
          >
            <template #icon><reload-outlined /></template>
            {{ searchType === 1 ? '换一批' : '重新搜索' }}
          </a-button>
          <a-button @click="shareResults">
            <template #icon><share-alt-outlined /></template>
            分享结果
          </a-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="memeData && (!memeData.res || memeData.res.length === 0)" class="empty-container">
        <a-empty description="没有找到相关表情包">
          <template #description>
            <span>尝试使用其他关键词或随机生成</span>
          </template>
          <a-button type="primary" @click="searchType = 1; getRandomMemes()">
            随机生成表情包
          </a-button>
        </a-empty>
      </div>

      <!-- 初始状态 -->
      <div v-else class="empty-container">
        <a-empty description="开始生成表情包">
          <template #description>
            <span>选择随机生成或输入关键词搜索</span>
          </template>
          <a-button type="primary" @click="getRandomMemes()">
            生成随机表情包
          </a-button>
        </a-empty>
      </div>
    </a-card>

    <!-- 图片预览 -->
    <a-image
      :visible="previewVisible"
      :src="previewImageUrl"
      :preview-visible="previewVisible"
      @visibleChange="handlePreviewVisibleChange"
    />

    <!-- 返回顶部 -->
    <a-back-top />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import {
  SmileOutlined,
  SearchOutlined,
  ThunderboltOutlined,
  EyeOutlined,
  DownloadOutlined,
  CopyOutlined,
  ReloadOutlined,
  ShareAltOutlined
} from '@ant-design/icons-vue';

// 状态定义
const memeData = ref(null);
const loading = ref(false);
const error = ref(null);
const searchType = ref(1); // 1=随机, 2=关键词搜索
const searchKeyword = ref('');
const randomLimit = ref(6);
const currentPage = ref(1);
const previewVisible = ref(false);
const previewImageUrl = ref('');

// 热门标签
const popularTags = ref(['可爱', '搞笑', '无语', '哭泣', '愤怒', '开心', '尴尬', '惊讶']);

// 监听搜索类型变化
watch(searchType, (newVal) => {
  // 切换到随机模式时，自动获取随机表情包
  if (newVal === 1) {
    getRandomMemes();
  }
});

// 获取随机表情包
const getRandomMemes = async () => {
  loading.value = true;
  error.value = null;

  try {
    const response = await axios.get('http://101.35.2.25/api/img/apihzbqb.php', {
      params: {
        id: '10003840',
        key: '036c2ab679bb366b2ad1b97ef2c5bd16',
        type: 1,
        limit: randomLimit.value
      },
      timeout: 10000
    });

    console.log('API响应:', response);

    if (response.data && response.data.code === 200) {
      memeData.value = response.data;
      message.success(`成功获取 ${response.data.res.length} 个随机表情包`);
    } else {
      error.value = response.data?.msg || '获取表情包失败';
      message.error(error.value);

      // 如果API失败，使用模拟数据
      fallbackToMockData();
    }
  } catch (err) {
    console.error('获取表情包失败:', err);
    error.value = `网络错误: ${err.message}`;
    message.error(error.value);

    // 如果API失败，使用模拟数据
    fallbackToMockData();
  } finally {
    loading.value = false;
  }
};

// 关键词搜索表情包
const searchMemes = async () => {
  if (searchType.value !== 2) return;
  if (!searchKeyword.value.trim()) {
    message.warning('请输入搜索关键词');
    return;
  }

  loading.value = true;
  error.value = null;

  try {
    const response = await axios.get('http://101.35.2.25/api/img/apihzbqb.php', {
      params: {
        id: '10003840',
        key: '036c2ab679bb366b2ad1b97ef2c5bd16',
        type: 2,
        words: encodeURIComponent(searchKeyword.value.trim()),
        page: currentPage.value,
        limit: 10
      },
      timeout: 10000
    });

    console.log('API响应:', response);

    if (response.data && response.data.code === 200) {
      memeData.value = response.data;
      if (response.data.res.length === 0) {
        message.info(`未找到「${searchKeyword.value}」相关表情包`);
      } else {
        message.success(`找到 ${response.data.count} 个「${searchKeyword.value}」相关表情包`);
      }
    } else {
      error.value = response.data?.msg || '搜索表情包失败';
      message.error(error.value);

      // 如果API失败，使用模拟数据
      fallbackToMockData(true);
    }
  } catch (err) {
    console.error('搜索表情包失败:', err);
    error.value = `网络错误: ${err.message}`;
    message.error(error.value);

    // 如果API失败，使用模拟数据
    fallbackToMockData(true);
  } finally {
    loading.value = false;
  }
};

// 快速搜索（点击标签）
const quickSearch = (tag) => {
  searchKeyword.value = tag;
  searchMemes();
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  searchMemes();
};

// 使用模拟数据（当API失败时）
const fallbackToMockData = (isSearch = false) => {
  const mockUrls = [
    'https://res.apihz.cn/img/bqb/81a0564e2225ee18ebc47774df9b0231.jpg',
    'https://res.apihz.cn/img/bqb/81a0624562b54c6c3a0c59c71be9a9db.jpg',
    'https://res.apihz.cn/img/bqb/81a10ec6cd169826ba0bd6149797bcc9.jpg',
    'https://res.apihz.cn/img/bqb/81a1dd421ff4d4c872798d2ffdc62ee7.jpg',
    'https://res.apihz.cn/img/bqb/81a22fdd1d382fd76ce8b28d73f8546a.jpg',
    'https://res.apihz.cn/img/bqb/81a35c91482940a358d2a2df0216dbe0.jpg'
  ];

  if (isSearch) {
    memeData.value = {
      code: 200,
      page: "1",
      maxpage: 2,
      count: "12",
      res: mockUrls.slice(0, 5)
    };
  } else {
    memeData.value = {
      code: 200,
      res: mockUrls.slice(0, randomLimit.value)
    };
  }

  message.info('使用模拟数据展示表情包');
};

// 处理图片加载错误
const handleImageError = (e, index) => {
  e.target.src = `https://via.placeholder.com/300x300?text=表情包${index+1}加载失败`;
};

// 预览图片
const previewImage = (url) => {
  previewImageUrl.value = url;
  previewVisible.value = true;
};

// 处理预览可见性变化
const handlePreviewVisibleChange = (visible) => {
  previewVisible.value = visible;
};

// 下载图片
const downloadImage = (url, index) => {
  const link = document.createElement('a');
  link.href = url;
  link.download = `表情包_${index+1}_${new Date().getTime()}.jpg`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  message.success('表情包下载已开始');
};

// 复制图片URL
const copyImageUrl = (url) => {
  navigator.clipboard.writeText(url)
    .then(() => {
      message.success('URL已复制到剪贴板');
    })
    .catch(err => {
      message.error('复制失败: ' + err);
    });
};

// 分享结果
const shareResults = () => {
  if (!memeData.value || !memeData.value.res || memeData.value.res.length === 0) return;

  const shareText = searchType.value === 1
    ? `我生成了${memeData.value.res.length}个随机表情包，快来看看吧！`
    : `我找到了${memeData.value.count}个「${searchKeyword.value}」相关表情包，快来看看吧！`;

  if (navigator.share) {
    navigator.share({
      title: '表情包分享',
      text: shareText,
      url: window.location.href,
    })
      .then(() => message.success('分享成功'))
      .catch((error) => message.error('分享失败: ' + error));
  } else {
    navigator.clipboard.writeText(shareText + ' ' + window.location.href)
      .then(() => {
        message.success('分享链接已复制，请手动分享');
      })
      .catch(err => {
        message.error('复制失败: ' + err);
      });
  }
};

// 截断URL显示
const truncateUrl = (url) => {
  if (url.length > 40) {
    return url.substring(0, 20) + '...' + url.substring(url.length - 20);
  }
  return url;
};

// 获取随机表情emoji
const getRandomEmoji = () => {
  const emojis = ['😂', '🤣', '😅', '😆', '😁', '😄', '😃', '😀', '😊', '😉', '😍', '🥰', '😘', '😗', '😙', '😚', '🙂', '🤔', '🤨', '😐', '😑', '😶', '🙄', '😏', '😒', '🤤', '😴', '🥴', '😵', '🤯', '🤠', '🥳'];
  return emojis[Math.floor(Math.random() * emojis.length)];
};

// 页面加载时自动获取随机表情包
onMounted(() => {
  getRandomMemes();
});
</script>

<style scoped>
.meme-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.meme-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: linear-gradient(to bottom, #ffffff, #f9f9f9);
}

.page-header {
  text-align: center;
  margin-bottom: 16px;
}

.title-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.emoji-title {
  font-size: 2rem;
}

.main-title {
  font-size: 2rem;
  font-weight: bold;
  background: linear-gradient(45deg, #722ed1, #13c2c2);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.subtitle {
  font-size: 1rem;
  color: #666;
  margin-top: 8px;
}

/* 搜索区域 */
.search-area {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-type {
  display: flex;
  margin-bottom: 16px;
  width: 100%;
}

.search-type :deep(.ant-radio-button-wrapper) {
  flex: 1;
  text-align: center;
}

.search-input-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-input {
  width: 100%;
}

.search-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.tag-label, .option-label {
  color: #666;
  font-size: 0.9rem;
}

.popular-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.popular-tag:hover {
  transform: scale(1.05);
}

.random-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.limit-slider {
  margin: 8px 0 16px;
}

.random-btn {
  align-self: center;
  height: 40px;
  padding: 0 24px;
  border-radius: 20px;
  background: linear-gradient(45deg, #722ed1, #13c2c2);
  border: none;
  box-shadow: 0 4px 12px rgba(114, 46, 209, 0.3);
  transition: all 0.3s;
}

.random-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(114, 46, 209, 0.4);
}

.loading-container, .error-container, .empty-container {
  padding: 60px 0;
  text-align: center;
}

.loading-content {
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
}

/* 表情包内容区域 */
.meme-content {
  animation: fadeIn 0.5s ease-in-out;
}

.result-info {
  margin-bottom: 20px;
}

.meme-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.meme-item {
  transition: all 0.3s;
}

.meme-card-item {
  height: 100%;
  border-radius: 12px;
  overflow: hidden;
}

.meme-image-container {
  position: relative;
  height: 280px;
  overflow: hidden;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.meme-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  cursor: pointer;
  transition: transform 0.3s;
}

.meme-image:hover {
  transform: scale(1.03);
}

.meme-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.meme-image-container:hover .meme-overlay {
  opacity: 1;
}

.meme-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.meme-emoji {
  font-size: 1.2rem;
}

.meme-url {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 0.8rem;
  color: #999;
}

.url-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
}

.copy-btn {
  padding: 0;
  height: auto;
}

.pagination-area {
  margin: 24px 0;
  text-align: center;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
  .meme-container {
    padding: 10px;
  }

  .main-title {
    font-size: 1.5rem;
  }

  .emoji-title {
    font-size: 1.5rem;
  }

  .meme-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }

  .meme-image-container {
    height: 180px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .action-buttons button {
    width: 100%;
  }

  .search-tags {
    justify-content: center;
  }
}
</style>
